package com.naihe.anderson.sms.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.naihe.anderson.sms.application.NhSmsApp;

public class FileUtil {

	/**
	 * @param logFile
	 * @param zipName
	 * @return
	 */
	static String zipLogFiles(File logFile, String zipName){
		try {
			String path = getLogPath();
			if(TextUtils.isEmpty(path)){
				return null;
			}
			File zipFile= new File(path + zipName);
			
			List<File> resFileList = new ArrayList<File>();
			resFileList.add(logFile);
			ZipUtils.zipFiles(resFileList, zipFile, "logs");
			return path;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * @return
	 */
	private static String getLogPath(){
		String path = "";
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			File sd = Environment.getExternalStorageDirectory();
			path = sd.getPath()+"/nhsms/";
		}
		return path;
	}
	
	public static String getPicNotePath(){
		String path = "";
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			File sd = Environment.getExternalStorageDirectory();
			path = sd.getPath()+"/nhsms/picnote/";
		}
		
		if(!TextUtils.isEmpty(path)){
			File dir = new File(path);
			if (!dir.exists()) {dir.mkdirs();}
		}
		return path;
	}
	
	private static File makeLogPath(String fileName) throws Exception{
		String path = getLogPath();
		
		if(TextUtils.isEmpty(path)){
			return null;
		}
		
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(path + fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
		return file;
	}
	
	private static synchronized void addErrorLog(Throwable error) throws Exception{
		StringBuffer logBuffer = new StringBuffer();
		
		StackTraceElement [] messages = error.getStackTrace();
		int length=messages.length;
		
		logBuffer.append("ERROR:=============");
		logBuffer.append(new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date()));
		logBuffer.append("========================\r\n");
		logBuffer.append(error.toString() + "\r\n");
		for(int i = 0 ; i < length ; i++){
			logBuffer.append(messages[i].toString() + "\r\n");
		}
		
		Throwable cause = error.getCause();
        if (cause != null) {
        	logBuffer.append("Caused by: " + cause.toString() + "\r\n");
        	StackTraceElement [] causeMessages = cause.getStackTrace();
			for(int i = 0 ; i < length ; i++){
				logBuffer.append(causeMessages[i].toString() + "\r\n");
			}
        }
        
		File file = makeLogPath("error.txt");
		if(file == null){
			logBuffer = null;
			return;
		}
		
		FileOutputStream fos = new FileOutputStream(file, true);
		fos.write(logBuffer.toString().getBytes());
		fos.flush();
		
		fos.close();
		fos = null;
		logBuffer = null;
	}
	/**
	 * 
	 * @param msg
	 * @param type
	 * @param classType
	 * @param tag
	 * @param error
	 */
	public static synchronized void addLog(String msg,Class<?> classType,String tag, Throwable error){
		if(!NhSmsApp.DEBUG_MODE){
			return;
		}
		
		StringBuffer logBuffer = new StringBuffer();
		FileOutputStream fos = null;
		try {
			if(error != null){
				addErrorLog(error);
				return;
			}
			
			logBuffer.append(new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date()));
			logBuffer.append("\t["+classType.getSimpleName()+"]" + msg + "\r\n");
			
			Log.d(tag, msg);
			
			File file = makeLogPath("logs.txt");
			if(file == null)
				return;
			
			if(file.length() > 10 * 1000 * 1000){
				fos = new FileOutputStream(file, false);
			} else {
				fos = new FileOutputStream(file, true);
			}
			fos.write(logBuffer.toString().getBytes());
			fos.flush();
			
			logBuffer =null;
			file = null;
		}catch (Exception e) { e.printStackTrace();}
		finally{
			try {
				if (fos != null){ fos.close(); fos = null;}
			} catch (IOException e) {}
		}
	}

    /**
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }

        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);

            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }
    
    public static void openFile(Context context, File f) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		context.startActivity(intent);
	}

	private static String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else {
			type = "*";
		}
		type += "/*";
		return type;
	}
}
